<template>
<div>
<common-head title="联系人列表"></common-head>
  <div class="warp">
    <van-contact-list
      v-model="chosenContactId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="switchContact"
    />
  </div>
</div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { fetchContactLists } from 'api'
import { getToken } from 'utils'
export default {
  name: 'contactLists',
  data () {
    return {
      chosenContactId: '-1',
      list: [
      ]
    }
  },
  created () {
    this.fetchContactLists()
  },
  beforeRouteEnter (to, from, next) {
    localStorage.setItem('from', from.path)
    next()
  },
  methods: {
    // 切换联系人
    switchContact (contact, index) {
      // console.log(contact, index)
      const from = localStorage.getItem('from')
      if (from === '/submitOrder') {
        this.$router.push({
          path: from,
          query: {
            id: contact.id
          }
        })
      }
    },
    onAdd () {
      this.$router.push('/contactAdd')
    },
    onEdit (contact) {
      // 可有参数，打印就是数据
      console.log(contact, 111)
      this.$router.push({
        path: '/contactUpdate',
        query: {
          id: contact.id
        }
      })
    },
    fetchContactLists () {
      fetchContactLists({
        token: getToken()
      }).then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          const contacts = res.data.data.result
          const contactArr = []
          contacts.forEach((contact) => {
            const obj = {}
            for (const key in contact) {
              switch (key) {
                case 'id':
                  obj.id = contact[key]
                  break
                case 'linkMan':
                  obj.name = contact[key]
                  break
                case 'mobile':
                  obj.tel = contact[key]
                  break
                case 'address':
                  obj.address = contact[key]
                  break
                case 'isDefault':
                  obj.isDefault = contact[key]
                  break
                default:
                  break
              }
            }
            contactArr.push(obj)
          })
          // console.log(contactArr)
          this.list = contactArr
          // 定义默认选中联系人id
          // this.chosenContactId = this.list.find(contact => contact.isDefault).id
          this.contacts = this.list.find(contact => contact.isDefault).id
          // 如果有默认联系人 选中id 就是 默认联系人id 否则 给第一个
          if (contacts) {
            this.chosenContactId = contacts.id
          } else {
            this.chosenContactId = this.list[0].id
          }
        }
      })
    }
  },
  components: { CommonHead }

}
</script>

<style lang="scss" scoped>
.warp{
  padding-top: 46px;
}
</style>
